//遍历树
export const publicTraverseTree = (node: any, callback: any) => {
  // 如果节点为空，则返回
  if (!node) return;
  callback(node);
  // 递归处理子节点
  if (node.children) {
    for (let i = 0; i < node.children.length; i++) {
      publicTraverseTree(node.children[i], callback);
    }
  }
};

export const fixedNum = (num: any, len: number = 2) => {
  // console.log(num)
  if (num === '' || num === undefined) {
    return '';
  }
  if (isNaN(num)) {
    return 0;
  }
  let res = 0;
  if (num) {
    res = Number(num);
  }
  return res.toFixed(len);
};

export function list2tree(list: any[], pName = 'parent_id') {
  let map: any = {};
  let node = [];
  let roots = [];
  for (let i = 0; i < list.length; i += 1) {
    map[list[i].id] = i; // 将列表中的id作为键，索引作为值存储在map中
    list[i].children = []; // 初始化子节点数组
  }
  for (let i = 0; i < list.length; i += 1) {
    node = list[i];
    if (node[pName]) {
      list[map[node[pName]]].children.push(node); // 将当前节点添加到其父节点的子节点数组中
    } else {
      roots.push(node); // 如果当前节点没有父节点，则将其添加到根节点数组中
    }
  }
  return roots;
}

export const empty = (obj: any) => {
  if (obj === null || obj === undefined || obj === false) {
    return true;
  }
  if (obj === 0 || obj === '') {
    return true;
  }
  if (typeof obj === 'object') {
    const str = JSON.stringify(obj);
    if (str === '{}' || str === '[]') {
      return true;
    }
  }
  return false;
};

export const tableSorter = (sorter: any) => {
  const fields = Object.keys(sorter);
  if (fields.length === 1) {
    const sortMap: any = { descend: 'desc', ascend: 'asc' };
    return `${fields[0]} ${sortMap[sorter[fields[0]]]}`;
  }
  return '';
};

export const tableDatePickerRange = (range: any) => {
  if (range) {
    return [range[0].format('YYYY-MM-DD'), range[1].format('YYYY-MM-DD')];
  }
  return '';
};

export const getBase64 = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};
